package com.ruoyi.web.controller.mstn;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.math.MathUtils;
import com.ruoyi.system.constant.ProjectStatus;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IMstnCatalystsService;
import com.ruoyi.system.service.IMstnSchemeBatchService;
import com.ruoyi.system.service.IMstnSchemeComputeResultService;
import com.ruoyi.system.service.IMstnSchemeComputeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

@RestController
@RequestMapping("/system/project/v2")
public class MstnProjectSchemeController extends BaseController {

    @Autowired
    private IMstnSchemeBatchService mstnSchemeBatchService;

    @Autowired
    private IMstnSchemeComputeService mstnSchemeComputeService;

    @Autowired
    private IMstnCatalystsService mstnCatalystsService;

    @Autowired
    private IMstnSchemeComputeResultService mstnSchemeComputeResultService;
    /**
     * 获取批次详情
     */
    @PreAuthorize("@ss.hasPermi('system:project:query')")
    @GetMapping("/{batchId}")
    public AjaxResult zv(@PathVariable Long batchId)
    {
        MstnSchemeBatch mstnSchemeBatch = mstnSchemeBatchService.selectMstnSchemeBatchByBatchId(batchId);
        mstnSchemeBatch.setComputeList(mstnSchemeComputeService.selectMstnSchemeComputeListByBatchId(batchId));
        return success(mstnSchemeBatch);
    }


    /**
     * 生成方案
     */
    @PreAuthorize("@ss.hasPermi('system:scheme:add')")
    @Log(title = "生成项目方案", businessType = BusinessType.INSERT)
    @PostMapping("/generate")
    public AjaxResult generateScheme(@RequestBody MstnSchemeBatch mstnSchemeBatch)
    {
        //生成批次
        mstnSchemeBatch.setCreateBy(getUsername());
        mstnSchemeBatch.setKeyboarder(getUsername());
        mstnSchemeBatch.setProjectStatus(ProjectStatus.PROJECT_STATUS_SCHEME);
        mstnSchemeBatch.setInputTime(DateUtils.getNowDate());
        mstnSchemeBatchService.insertMstnSchemeBatch(mstnSchemeBatch);

        //选择对应型号得催化剂数据，为ZV计算做准备
        CatalystsMiddleResult catalysts = mstnCatalystsService.selectMstnCatalystsArea(new CatalystsMiddleResult(mstnSchemeBatch.getCatalystsName(), mstnSchemeBatch.getCategoryName(), mstnSchemeBatch.getLifetime()));
        mstnSchemeBatch.getComputeList().forEach(compute -> {
            compute.setBatchId(mstnSchemeBatch.getBatchId());
            compute.setProjectId(mstnSchemeBatch.getProjectId());
            //寿命到期时的脱销效率
            BigDecimal efficiency = MathUtils.efficiency(compute.getNox(), mstnSchemeBatch.getOutNox());
            BigDecimal zv = MathUtils.zv2(compute.getQuantityFlow(),catalysts.getK(),catalysts.getK0(),catalysts.getGeometryAreaRate(),efficiency);
            compute.setZv(zv);
        });
        mstnSchemeComputeService.insertMstnSchemeComputeList(mstnSchemeBatch.getComputeList());

        return success(mstnSchemeBatch.getBatchId());
    }

    @PreAuthorize("@ss.hasPermi('system:scheme:edit')")
    @Log(title = "设置流速", businessType = BusinessType.UPDATE)
    @PutMapping("/setFlow")
    public AjaxResult setFlow(@RequestBody MstnSchemeCompute mstnSchemeCompute)
    {
        MstnSchemeCompute dbMstnSchemeCompute = mstnSchemeComputeService.selectMstnSchemeComputeBySchemeComputeId(mstnSchemeCompute.getSchemeComputeId());
        mstnSchemeCompute.setS(MathUtils.s(dbMstnSchemeCompute.getQuantityFlow(), mstnSchemeCompute.getFlowRate()));
//        mstnSchemeCompute.setCatalystsH(dbMstnSchemeCompute.getZv().divide(mstnSchemeCompute.getS(), 2, RoundingMode.HALF_UP));
        return toAjax(mstnSchemeComputeService.updateMstnSchemeCompute(mstnSchemeCompute));
    }

    /**
     * 获取阵列尺寸
     * @param mstnSchemeCompute
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:scheme:query')")
    @GetMapping("/getMatrixSize")
    public AjaxResult getMatrixSize(@RequestBody MstnSchemeCompute mstnSchemeCompute)
    {
        MstnSchemeCompute result = new MstnSchemeCompute();
        if (mstnSchemeCompute.getReactorL() == null || mstnSchemeCompute.getReactorW() == null){
            MstnSchemeCompute dbMstnSchemeCompute = mstnSchemeComputeService.selectMstnSchemeComputeBySchemeComputeId(mstnSchemeCompute.getSchemeComputeId());
            result.setSuggestMatrixX(MathUtils.sqrt(dbMstnSchemeCompute.getS()).divide(new BigDecimal("0.466"), 2, RoundingMode.HALF_UP));
            result.setSuggestMatrixY(MathUtils.sqrt(dbMstnSchemeCompute.getS()).divide(new BigDecimal("0.466"), 2, RoundingMode.HALF_UP));
        }else {
            result.setSuggestMatrixX(new BigDecimal(mstnSchemeCompute.getReactorL()).divide(new BigDecimal("466"), 2, RoundingMode.HALF_UP));
            result.setSuggestMatrixY(new BigDecimal(mstnSchemeCompute.getReactorW()).divide(new BigDecimal("466"), 2, RoundingMode.HALF_UP));
        }
        return success(result);
    }

    @PreAuthorize("@ss.hasPermi('system:scheme:edit')")
    @Log(title = "核校面积", businessType = BusinessType.UPDATE)
    @PostMapping("/checkArea")
    public AjaxResult checkArea(@RequestBody MstnSchemeCompute mstnSchemeCompute)
    {
        MstnSchemeCompute dbMstnSchemeCompute = mstnSchemeComputeService.selectMstnSchemeComputeBySchemeComputeId(mstnSchemeCompute.getSchemeComputeId());

        return success(MathUtils.check(mstnSchemeCompute.getMatrixX(), mstnSchemeCompute.getMatrixY(), dbMstnSchemeCompute.getS()));
    }

    @PreAuthorize("@ss.hasPermi('system:scheme:edit')")
    @Log(title = "确认参数,获取建议高度", businessType = BusinessType.UPDATE)
    @PutMapping("/getSuggestH")
    public AjaxResult getSuggestH(@RequestBody MstnSchemeCompute mstnSchemeCompute)
    {
        MstnSchemeCompute dbMstnSchemeCompute = mstnSchemeComputeService.selectMstnSchemeComputeBySchemeComputeId(mstnSchemeCompute.getSchemeComputeId());
        if (mstnSchemeCompute.getNeedCheck() == null || mstnSchemeCompute.getNeedCheck()) {
            if (!MathUtils.check(mstnSchemeCompute.getMatrixX(), mstnSchemeCompute.getMatrixY(), dbMstnSchemeCompute.getS())) {
                return error("面积核校未通过");
            }
        }
        mstnSchemeComputeService.updateMstnSchemeCompute(mstnSchemeCompute);
        MstnSchemeCompute result = new MstnSchemeCompute();
        BigDecimal s = new BigDecimal(mstnSchemeCompute.getMatrixX() * mstnSchemeCompute.getMatrixY()).multiply( new BigDecimal("0.466")).multiply(new BigDecimal("0.466"));
        result.setSuggestH(dbMstnSchemeCompute.getZv().multiply(new BigDecimal("1000")).divide(s, 2, RoundingMode.HALF_UP));
        return success(result);
    }

    /**
     * 获取催化剂
     * @param mstnSchemeCompute
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:scheme:query')")
    @GetMapping("/getCatalysts")
    public AjaxResult getCatalysts(@RequestBody MstnSchemeCompute mstnSchemeCompute)
    {
        BigDecimal h = mstnSchemeCompute.getCatalystsH();
        String moduleName = MathUtils.switchCatalystsType(h);
        //计算时需要除1000
//        mstnSchemeCompute.setCatalystsH(mstnSchemeCompute.getCatalystsH().divide(new BigDecimal("1000"), 2, RoundingMode.HALF_UP));
//        mstnSchemeComputeService.updateMstnSchemeCompute(mstnSchemeCompute);
        MstnSchemeCompute dbMstnSchemeCompute = mstnSchemeComputeService.selectMstnSchemeComputeBySchemeComputeId(mstnSchemeCompute.getSchemeComputeId());

        MstnSchemeBatch mstnSchemeBatch = mstnSchemeBatchService.selectMstnSchemeBatchByBatchId(dbMstnSchemeCompute.getBatchId());
        List<MstnCatalysts > catalystsList = mstnCatalystsService.selectMstnCatalystsList(new MstnCatalysts(mstnSchemeBatch.getCategoryName(), mstnSchemeBatch.getCatalystsName(),  moduleName));
        if (!catalystsList.isEmpty()) {
            return success(catalystsList.get(0));
        } else {
            //向下选择
            return success(mstnCatalystsService.selectCatalystsByNextHeight(mstnSchemeBatch.getCategoryName(),mstnSchemeBatch.getCatalystsName(), h));
        }
    }

    /**
     * 设置层数
     * @param mstnSchemeCompute
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:scheme:edit')")
    @Log(title = "设置层数", businessType = BusinessType.UPDATE)
    @PutMapping("/setFloors")
    public AjaxResult setFloors(@RequestBody MstnSchemeCompute mstnSchemeCompute)
    {
        MstnSchemeCompute dbMstnSchemeCompute = mstnSchemeComputeService.selectMstnSchemeComputeBySchemeComputeId(mstnSchemeCompute.getSchemeComputeId());
        mstnSchemeCompute.setCatalystsN(new BigDecimal(dbMstnSchemeCompute.getMatrixX() * dbMstnSchemeCompute.getMatrixY() * mstnSchemeCompute.getFloors()));

        return toAjax(mstnSchemeComputeService.updateMstnSchemeCompute(mstnSchemeCompute));
    }

    @PreAuthorize("@ss.hasPermi('system:scheme:edit')")
    @Log(title = "设置催化剂", businessType = BusinessType.UPDATE)
    @PutMapping("/setCatalysts")
    public AjaxResult setCatalysts(@RequestBody MstnSchemeCompute mstnSchemeCompute)
    {
        if (mstnSchemeCompute.getModuleName().isEmpty()) {
            return error("催化剂名称不能为空");
        }
        MstnSchemeCompute dbMstnSchemeCompute = mstnSchemeComputeService.selectMstnSchemeComputeBySchemeComputeId(mstnSchemeCompute.getSchemeComputeId());
        MstnSchemeBatch dbSchemeBatch = mstnSchemeBatchService.selectMstnSchemeBatchByBatchId(dbMstnSchemeCompute.getBatchId());

        List<MstnCatalysts > catalystsList = mstnCatalystsService.selectMstnCatalystsList(new MstnCatalysts(dbSchemeBatch.getCategoryName(),dbSchemeBatch.getCatalystsName(),  mstnSchemeCompute.getModuleName()));
        if (catalystsList.isEmpty()){
            return error("未找到匹配的催化剂");
        }
//        MstnCatalysts catalysts = catalystsList.get(0);
        BigDecimal catalystsH = catalystsList.stream().map(MstnCatalysts::getCatalystsH).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
        mstnSchemeCompute.setCatalystsH(catalystsH.divide(new BigDecimal("1000"), 2, RoundingMode.HALF_UP));
        mstnSchemeCompute.setVc(MathUtils.vc(mstnSchemeCompute.getCatalystsH(), dbMstnSchemeCompute.getCatalystsN()));
        mstnSchemeCompute.setRc(MathUtils.rc(mstnSchemeCompute.getVc(), dbMstnSchemeCompute.getZv()));
        mstnSchemeCompute.setSelectModuleName(mstnSchemeCompute.getModuleName());
        return toAjax(mstnSchemeComputeService.updateMstnSchemeCompute(mstnSchemeCompute));
    }

    @PreAuthorize("@ss.hasPermi('system:scheme:edit')")
    @Log(title = "生成", businessType = BusinessType.UPDATE)
    @PostMapping("/submit")
    public AjaxResult submit(@RequestBody MstnSchemeCompute mstnSchemeCompute)
    {
        MstnSchemeCompute dbMstnSchemeCompute = mstnSchemeComputeService.selectMstnSchemeComputeBySchemeComputeId(mstnSchemeCompute.getSchemeComputeId());
        MstnSchemeBatch dbSchemeBatch = mstnSchemeBatchService.selectMstnSchemeBatchByBatchId(dbMstnSchemeCompute.getBatchId());
        List<MstnCatalysts > catalystsList = mstnCatalystsService.selectMstnCatalystsList(new MstnCatalysts(dbSchemeBatch.getCategoryName(),dbSchemeBatch.getCatalystsName(),  dbMstnSchemeCompute.getSelectModuleName()));
        if (catalystsList.isEmpty()){
            return error("未找到匹配的催化剂");
        }
        for (MstnCatalysts catalysts : catalystsList) {
            MstnSchemeComputeResult mstnSchemeComputeResult = new MstnSchemeComputeResult();
            mstnSchemeComputeResult.setProjectId(dbSchemeBatch.getProjectId());
            //工况
            mstnSchemeComputeResult.setConditionType(mstnSchemeCompute.getConditionType());
            //催化剂id
            mstnSchemeComputeResult.setCatalystsId(catalysts.getCatalystsId());
            //型号
            mstnSchemeComputeResult.setCategoryName(catalysts.getCategoryName());
            //催化剂名称
            mstnSchemeComputeResult.setCatalystsName(catalysts.getCatalystsName());
            //每台催化剂体积  V=ZV/JZ
            mstnSchemeComputeResult.setCatalystsVolume(dbMstnSchemeCompute.getVc().multiply(new BigDecimal(dbSchemeBatch.getReactorCount())));
            //机组数量 JZ
            mstnSchemeComputeResult.setGroupCount(dbSchemeBatch.getGroupCount());
            //催化剂总体积
            mstnSchemeComputeResult.setCatalystTotalVolume(dbMstnSchemeCompute.getVc());
            //每台机组反应器数
            mstnSchemeComputeResult.setReactorCount(dbSchemeBatch.getReactorCount());
            //每台反应器催化剂体积 DV = V /FYQ
            mstnSchemeComputeResult.setSingleReactorCatalystsVolume(mstnSchemeComputeResult.getCatalystsVolume().divide(new BigDecimal(dbSchemeBatch.getReactorCount()), 2 , RoundingMode.HALF_UP));
            //催化剂层数
            mstnSchemeComputeResult.setReactorFloor(dbMstnSchemeCompute.getFloors());
            //催化剂单元阵列
            mstnSchemeComputeResult.setUnitMatrixCount(dbMstnSchemeCompute.getMatrixX()+"*"+dbMstnSchemeCompute.getMatrixY());
            //每台反应器每层催化剂单元数量
            mstnSchemeComputeResult.setMinReactorUnitVolume(dbMstnSchemeCompute.getMatrixX() * dbMstnSchemeCompute.getMatrixY());
            //模块型号
            mstnSchemeComputeResult.setModuleName(catalysts.getModuleName());
            //模块尺寸
            mstnSchemeComputeResult.setModuleSize(catalysts.getModuleL().toString() + "*" + catalysts.getModuleW().toString() + "*" + catalysts.getModuleH().toString());
            //每层净催化剂高度
            mstnSchemeComputeResult.setCatalystsHeight(catalysts.getCatalystsH());
            //反应器尺寸
            mstnSchemeComputeResult.setReactorSize(dbMstnSchemeCompute.getReactorL() + "*" + dbMstnSchemeCompute.getReactorW());
            //每个模块的毛重
            mstnSchemeComputeResult.setWeight(catalysts.getModuleKg());
            mstnSchemeComputeResult.setErrorRate(catalysts.getErrorRate());
            //每台反应器内催化剂模块总数
            mstnSchemeComputeResult.setSingleReactorUnitCount(dbMstnSchemeCompute.getMatrixX() * dbMstnSchemeCompute.getMatrixY() * dbMstnSchemeCompute.getFloors());
            //每台反应器内模块的总毛总
            mstnSchemeComputeResult.setTotalWeight(catalysts.getModuleKg().multiply(new BigDecimal(mstnSchemeComputeResult.getSingleReactorUnitCount())));
            mstnSchemeComputeResult.setRemark(mstnSchemeCompute.getRemark());
            mstnSchemeComputeResult.setPrecondition(mstnSchemeCompute.getPrecondition());
            mstnSchemeComputeResult.setBatchId(dbSchemeBatch.getBatchId());
            mstnSchemeComputeResultService.insertMstnSchemeComputeResult(mstnSchemeComputeResult);
        }
        MstnCatalysts catalysts = catalystsList.get(0);
//        if (MathUtils.checkRc(dbMstnSchemeCompute.getRc())){


            //更新项目状态
            dbSchemeBatch.setProjectStatus(ProjectStatus.PROJECT_STATUS_TECHNICAL);
            mstnSchemeBatchService.updateMstnSchemeBatch(dbSchemeBatch);
            return success();
//        } else {
//            return error("实际余量核校未通过");
//        }
    }

    @PreAuthorize("@ss.hasPermi('system:scheme:edit')")
    @Log(title = "重置计算", businessType = BusinessType.UPDATE)
    @PutMapping("/reset")
    public AjaxResult reset(@RequestBody MstnSchemeCompute mstnSchemeCompute)
    {
        mstnSchemeComputeService.restWithComputeId(mstnSchemeCompute.getSchemeComputeId());
        return success();
    }

}
